package leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-11-13 11:46
 **/
public class LeetCode54 {

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        int m = matrix.length;
        if (m == 0) {
            return list;
        }
        int n = matrix[0].length;
        if (n == 0) {
            return list;
        }
        //元素的个数
        int count = m * n;
        //轮数
        int k = 0;
        int i = 0;
        int j = 0;
        while (count > 0) {
            for (; j < n - k && count > 0; j++) {
                list.add(matrix[i][j]);
                count--;
            }
            j--;
            i++;

            for (; i < m - k && count > 0; i++) {
                list.add(matrix[i][j]);
                count--;
            }
            i--;
            j--;

            for (; j >= k && count > 0; j--) {
                list.add(matrix[i][j]);
                count--;
            }
            j++;
            i--;

            for (; i >= k + 1 && count > 0; i--) {
                list.add(matrix[i][j]);
                count--;
            }
            i++;
            j++;
            k++;

        }
        return list;
    }

}
